package com.java.study.boot;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

/**
 * @author Spencer Gibb
 */
@Component
public class AuthenticateGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    AntPathMatcher antPathMatcher = new AntPathMatcher();


    public static void main(String[] args) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        System.out.println(antPathMatcher.match("qq/{**/*/**", "qq/asfsa/232/werw/sdf"));
        System.out.println(antPathMatcher.matchStart("/aa/qq/aa/dd","/aa/qq"));
        System.out.println(antPathMatcher.extractPathWithinPattern("/aa/*/aa/dd","/aa/qq"));

        System.out.println(antPathMatcher.isPattern("/aa/{1}"));
    }

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            String value = ServerWebExchangeUtils.expand(exchange, config.getValue());

            ServerHttpRequest request = exchange.getRequest().mutate()
                    .headers(httpHeaders -> httpHeaders.add(config.getName(), value))
                    .build();

            return chain.filter(exchange.mutate().request(request).build());
        };
    }

}

